import { memo, forwardRef, useState, useImperativeHandle, ForwardRefRenderFunction, useMemo, useCallback } from 'react'
import { Modal, Form, message } from 'antd'
import { HsAdminForm } from '@hs-admin/base-components'
import { reqDataDomainAdd, reqDataDomainEdit } from '@/api/assetMaintain/industry/domain'

interface Props {
  finish: () => void
}
const TableEdit: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { finish } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [formValues, setformValues] = useState<any>({})
  const [modalType, setmodalType] = useState('新增')
  const formItemOptions = useMemo(
    () => [
      {
        label: '领域名称',
        name: 'name',
        required: true,
        component: 'Input'
      },
      {
        label: '领域描述',
        name: 'description',
        required: true,
        component: 'TextArea'
      }
    ],
    []
  )

  const handleOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        const params: any = {
          id: formValues.id,
          ...values
        }
        let callFn = reqDataDomainAdd
        let text = '新增成功'
        if (params.id) {
          callFn = reqDataDomainEdit
          text = '编辑成功'
        }
        await callFn(params)
        message.success(text)
        finish()
        handleCancel()
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const handleCancel = () => {
    setmodalType('新增')
    form.resetFields()
    setformValues({})
    setIsModalOpen(false)
  }
  const showModal = useCallback(
    (item: any) => {
      if (item) {
        form.setFieldsValue(item)
        setformValues(item)
        setmodalType('编辑')
      }
      setIsModalOpen(true)
    },
    [form]
  )

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    [showModal]
  )

  return (
    <Modal title={`${modalType}领域`} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} />
    </Modal>
  )
}

export default memo(forwardRef(TableEdit))
